package com.gitee.lichoking.mysoap.common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 映射器注册
 *
 * @Author lich
 * @Date 2021/6/3
 **/
public class MapperRegistry {
    private final Configuration configuration;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new ConcurrentHashMap<>();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<T> mapperInterface) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(mapperInterface);
        if (mapperProxyFactory == null) {
            synchronized (knownMappers) {
                if (knownMappers.get(mapperInterface) == null) {
                    mapperProxyFactory = new MapperProxyFactory<>(configuration, mapperInterface);
                    knownMappers.put(mapperInterface, mapperProxyFactory);
                }
            }
        }
        final MapperProxy<T> mapperProxy = new MapperProxy<>(configuration, mapperInterface);
        return (T) mapperProxyFactory.newInstance(mapperProxy);
    }
}
